package me.jessyan.armscomponent.commonsdk.utils;

import android.text.TextUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author: xuwei
 * @Date: 2020/10/30 13:54
 * @Description: 字符串处理相关类
 */
public class StringUtil {

    /**
     * 正则表达式判断是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");

        return pattern.matcher(str).matches();
    }

    public static String setContent(String content) {
        if (TextUtils.isEmpty(content)) {
            return "--";
        }
        return content;
    }

    //将","分割的字符串转成数组
    public static String[] splitString(String content) {
        if (TextUtils.isEmpty(content)) {
            return null;
        }
        return content.split(",");
    }

    //将list转成用","分割的字符串
    public static String listToString(List<String> list) {
        if (list == null || list.size() == 0) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : list) {
            if (!TextUtils.isEmpty(s)) {
                stringBuilder.append(s).append(",");
            }
        }
        if (!TextUtils.isEmpty(stringBuilder.toString())) {
            return stringBuilder.substring(0, stringBuilder.toString().length() - 1);
        }
        return "";
    }

    // 数字保留N为有效小数数字, 四舍五入
    public static String numberToScale(double sourceNumber, int scale){
        BigDecimal bigDecimal = new BigDecimal(sourceNumber);
        double value = bigDecimal.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        DecimalFormat df = new DecimalFormat("#0.00");
        String valueStr = df.format(value);
        return valueStr;
    }

    // 数字保留N为有效小数数字, 四舍五入
    public static String numberToScale(String sourceNumber, int scale){
        try{
            double douValue = Double.valueOf(sourceNumber);
            BigDecimal bigDecimal = new BigDecimal(douValue);
            double value = bigDecimal.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
            DecimalFormat df = new DecimalFormat("#0.00");
            String valueStr = df.format(value);
            return valueStr;
        }catch (Exception e){
            return "0.00";
        }
    }
}
